<?php

namespace App\Models\Train\TrainPoints\Repositories;

use App\Models\Train\TrainPoints\Repositories\Interfaces\TrainPointsRepositoryInterface;
use App\Models\Train\TrainPoints\TrainPoint;
use App\Trip\Repository\BaseRepository;
use Illuminate\Support\Collection;

class TrainPointsRepository extends BaseRepository implements TrainPointsRepositoryInterface
{
    public function __construct(TrainPoint $model)
    {
        parent::__construct($model);
    }

    public function addPoint(array $data): TrainPoint
    {
        $point = $this->findByTrainCodeAndStationCode($data['train_code'], $data['station_code']);
        if ($point) {
            if ($point->state == 0) {
                $this->updatePoint($point, $data);
            }
            return $point;
        }
        return $this->create($data);
    }

    public function findByTrainCodeAndStationCode(string $train_code, string $station_code): ?TrainPoint
    {
        return $this->findOneBy([
            'train_code'   => $train_code,
            'station_code' => $station_code,
        ]);
    }

    public function updatePoint(TrainPoint $point, array $data): bool
    {
        return $this->update($data, $point);
    }

    public function listByTrainCode(string $train_code): Collection
    {
        return $this->model
            ->where('train_code', $train_code)
            ->orderBy('sequence')
            ->get();
    }
}